package com.sujiewon.salesadmin.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

import com.ibatis.common.logging.LogFactory;

public class DownloadView extends AbstractView {

	private Log log = (Log) LogFactory.getLog(this.getClass());
	
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		File file = (File)model.get("downloadFile");
		response.setContentType(getContentType());
		response.setContentLength((int)file.length());
		response.setHeader("Content-Tranfer-Encoding", "binary");
		
		log.debug("FILE URL + " + file.getName());
		
		response.setHeader("Content-Dispostion", "attachment;fileName=\"" + 
				new String(file.getName().getBytes("euc-kr"), "latin1") + "\";");
		OutputStream out = response.getOutputStream();
		FileInputStream fis = null;
		
		try{
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
		} catch(IOException e){
			log.debug("FILE IS NO EXIST.");
			e.printStackTrace();
		} finally{
			if(fis != null){
				fis.close();
			}
		}
		out.flush();
	}
}
